<?php

session_start();

if (!$_SESSION['WEIBOUSERINFO']) {  // 判断用户是否已经使用第三方账号登陆

    define( "WB_AKEY" , '670979742' );
    define( "WB_SKEY" , '9250bb3f8a331612ce2ec28ff27efbb2' );

    //include_once( 'oauth2/sina/config.php' );
    include_once( 'oauth2/sina/saetv2.ex.class.php' );

    //  当前页面的URL
    $pageURL = 'http';
    if ($_SERVER["HTTPS"] == "on") {
        $pageURL .= "s";
    }
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }
    //$tempURL = $pageURL;
    //echo "==================".$pageURL;
    define( "WB_CALLBACK_URL" , $pageURL);  //  把回调URL设置为当前页面的URL，是的用户登录成功之后还是回到本页面

    $o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );
    $code_url = $o->getAuthorizeURL( WB_CALLBACK_URL );  //  解析回调URL中的code参数

    //$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );
    //  当用户授权之后返回到本页面时候已经有参数code
    if (isset($_REQUEST['code'])) {
        $keys = array();
        $keys['code'] = $_REQUEST['code'];
        $keys['redirect_uri'] = WB_CALLBACK_URL;
        try {
            $token = $o->getAccessToken( 'code', $keys ) ;
        } catch (OAuthException $e) {
        }

        if ($token) {  //授权成功
            $_SESSION['token'] = $token;
            setcookie( 'weibojs_'.$o->client_id, http_build_query($token) );
            //  获取登录用户的信息
            $c = new SaeTClientV2( WB_AKEY , WB_SKEY , $_SESSION['token']['access_token'] );
            $ms  = $c->home_timeline(); // done
            $uid_get = $c->get_uid();
            $uid = $uid_get['uid'];
            $user_message = $c->show_user_by_id( $uid);//根据ID获取用户等基本信息
            //var_dump($user_message);
            //  登录成功后把用户信息保存到session
            $data['wbusername'] = $user_message['screen_name'];  //昵称
            $data['wbuserheadpic'] = $user_message['profile_image_url'];  // 头像
            $data['wbuserwebsite'] = $user_message['url'];//  url
            $_SESSION['WEIBOUSERINFO'] = $data;
            
            //  去掉URL上的code，安全考虑
            $arr = explode('&code=', $pageURL); 
            header("Location:$arr[0]");
            //exit;

        } else {  //
        }
    } else {  //
    }
} else {  //用户已经登录
}


?>